package com.zttek.photosShareProject.modules.service.share.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.zttek.photosShareProject.common.json.ImageVO;
import com.zttek.photosShareProject.common.json.UserVO;
import com.zttek.photosShareProject.common.json.VO;
import com.zttek.photosShareProject.common.myException.DBException;
import com.zttek.photosShareProject.modules.mapper.ImageMapper;
import com.zttek.photosShareProject.modules.model.Image;
import com.zttek.photosShareProject.modules.model.Share;
import com.zttek.photosShareProject.modules.model.User;
import com.zttek.photosShareProject.modules.service.login.IUserService;
import com.zttek.photosShareProject.modules.service.share.IImageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Y on 2017/8/29.
 */
@Service
public class ImageService implements IImageService {

    @Autowired
    private ImageMapper imageMapper;

    @Autowired
    private IUserService userService;

    @Transactional
    @Override
    public Image newImage(String type, String path, String thumbPath, Long userId, String md5) throws Exception {
        Image image = new Image();
        image.setType(type);
        image.setPath(path);
        image.setThumbPath(thumbPath);
        image.setUserId(userId);
        image.setMd5String(md5);
        imageMapper.insert(image);
        return image;
    }

    @Override
    public List<Image> selectImagesByIds(String idsString) throws Exception {
        Long[] ids = VO.divideLongIds(idsString);
        EntityWrapper<Image> ew = new EntityWrapper<>();
        ew.in("id",ids);
//        List<Image> list = imageSelectList(ew);
        return imageMapper.selectList(ew);
    }

    @Override
    public Image selectImageById(Long imageId) throws Exception {
//        Image image = imageSelectById(imageId);
        return imageMapper.selectById(imageId);
    }

    @Transactional
    @Override
    public void deleteImageById(Long imageId) throws Exception {
//        Image image = imageSelectById(imageId);
        Image image = imageMapper.selectById(imageId);
        image.setValid(0);
        imageMapper.updateById(image);
    }

    @Override
    public Image checkMd5(String md5) throws Exception {
        EntityWrapper<Image> ew = new EntityWrapper<>();
        ew.in("md5_string", md5);
        List<Image> images = imageMapper.selectList(ew);
        if (images.size() == 0)
            return null;
        else
            return images.get(0);
    }

    @Override
    public ImageVO image2VO(Image image, boolean withUser) throws Exception {
        UserVO userVO = null;
        if (withUser) {
            User user = userService.selectUserById(image.getUserId());
            userVO = new UserVO(user, null, false);
        }
        return new ImageVO(image, userVO);
    }

    @Override
    public List<ImageVO> image2VO(List<Image> images, boolean withUser) throws Exception {
        List<ImageVO> list = new ArrayList<>();
        for (Image image : images) {
            list.add(image2VO(image, withUser));
        }
        return list;
    }

    @Override
    public String getImageMD5Val(MultipartFile multipartFile) throws Exception {
        InputStream fis = multipartFile.getInputStream();
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] buffer = new byte[1024];
        int length = -1;
        while ((length = fis.read(buffer, 0, 1024)) != -1) {
            md.update(buffer, 0, length);
        }
        BigInteger bigInt = new BigInteger(1, md.digest());
        System.out.println("文件md5值：" + bigInt.toString(16));
        return bigInt.toString(16);
        //210e3e398fadadfe1d305371cb0dcf64
    }

//    /**
//     * 分割ids字符串
//     * @param idsString *
//     * @return *
//     */
//    public static Long[] divideLongIds(String idsString) {
//        System.out.println("h :"+idsString);
//        String[] idsTemp = idsString.split(",");
//        Long[] ids = new Long[idsTemp.length];
//        //System.out.println("length："+idsTemp.length);
//        for(int i = 0;i<idsTemp.length;i++){
//            ids[i] = Long.parseLong(idsTemp[i].trim());
//        }
//        return ids;
//    }
//
//    /**
//     * 合并id数组
//     * @param ids *
//     * @return *
//     */
//    public static String mergeIds(Long[] ids){
//        String idsString = "";
//        idsString += ids[0];
//        String separator = ",";
//        for(int i = 1;i<ids.length;i++){
//            idsString += separator+ids[i];
//        }
//        //System.out.println(idsString);
//        return idsString;
//    }

    @Deprecated
    private Image imageSelectById(long imageId){
        Image image = null;
        try {
            image = imageMapper.selectById(imageId);
        }catch (Exception e){
            e.printStackTrace();
            throw new DBException(DBException.IMAGE_SELECT_FAILURE);
        }
        return image;
    }

    @Deprecated
    private void imageInsert(Image image){
        try {
            imageMapper.insert(image);
        }catch (Exception e){
            e.printStackTrace();
            throw new DBException(DBException.IMAGE_INSERT_FAILURE);
        }
    }

    @Deprecated
    private void imageUpdate(Image image){
        try {
            imageMapper.updateById(image);
        }catch (Exception e){
            e.printStackTrace();
            throw new DBException(DBException.IMAGE_UPDATE_FAILURE);
        }
    }

    @Deprecated
    private List<Image> imageSelectList(EntityWrapper<Image> ew){
        List<Image> images = null;
        try {
            images = imageMapper.selectList(ew);
        }catch (Exception e){
            e.printStackTrace();
            throw new DBException(DBException.IMAGE_SELECT_FAILURE);
        }
        return images;
    }
}
